const { CHUNK_SIZE } = require('../const');
const fs = require('fs');


function pipeStream(fromPath, targetPath, index) {
    return new Promise(resolve => {
        const readStream = fs.createReadStream(fromPath);
        const writeStream = fs.createWriteStream(targetPath, {
            start: index * CHUNK_SIZE
        });

        readStream.pipe(writeStream);
        readStream.on('end', () => {
            fs.unlink(fromPath, (err) => {
                if (err) {
                    console.log(err);
                }
            });
            resolve();
        });
    });
}

function recombinationFileName(fileHash, filename) {
    const matchResult = filename.match(/(.+)\.(\w+)$/);
    const ext = matchResult && matchResult[2];

    let res = fileHash;

    if (ext) {
        res += '.' + ext;
    }
    return res;
}

/**
 * 获取文件拓展名
 * @param {string} filename
 * @returns {string}
 */
function extractExt(filename) {
    return filename.slice(filename.lastIndexOf('.'), filename.length);
}

module.exports = {
    pipeStream,
    recombinationFileName,
    extractExt
};